package com.mishow.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;


/**
 * 作者：wei.miao <br/>
 * 描述：SD卡文件管理类
 */
public class FileUtil {
	// SD卡文件根目录名称
	public final static String ROOT_DIRECTORY = "mishow";
	// 图片缓存目录
	public final static String IMAGECACHE = "imagecache";
	// 录音文件目录
	public static final String SPEEX_PATH = "speex";
	// 异常文件目录
	public static final String CRASH_PATH = "crash";
	// 语音评测文件目录
	public static final String ISE_PATH = "ise";
	// Apk的更新目录
	public static final String APK_UPDATE_PATH = "apk_update";
	// 图片目录
	public static final String IMAGE_PATH = "image";
	
	private static java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
	
	private static final int MB = 1024 * 1024;

	// 图片缓存的SD卡路径
	public static String getImageCachePath() {
		return Environment.getExternalStorageDirectory() + File.separator + ROOT_DIRECTORY + File.separator + IMAGECACHE;
	}
	
	/**
	 * 获取sdcard目录或者文件路径
	 * @param directoryPath
	 * @param fileName
	 * @return
	 */
	public static String getDirectoryFilePath(String directoryPath, String fileName){
		String sdPath = getSdcardPath();
		if( sdPath == null){
			return null;
		}
		StringBuffer stringBuffer = new StringBuffer(sdPath).append(File.separator).append(ROOT_DIRECTORY);
		if( directoryPath != null){
			stringBuffer.append(File.separator).append(directoryPath);
		}
		if( fileName != null){
			stringBuffer.append(File.separator).append(fileName);
		}
		return stringBuffer.toString();
	}
		

	/**
	 * 获取缓存图片文件夹的大小
	 * @return
	 */
	public static String getImageCacheSize() {
		String sizeString = "0M";
		long dirSize = 0;
		String path = Environment.getExternalStorageDirectory()
				+ File.separator + ROOT_DIRECTORY + File.separator + IMAGECACHE;
		File dir = new File(path);
		if (dir.exists()) {
			if (!dir.isDirectory()) {
				return sizeString;
			}
			File[] files = dir.listFiles();
			for (File file : files) {
				if (file.isFile()) {
					dirSize += file.length();
				} else if (file.isDirectory()) {
					dirSize += file.length();
				}
			}
		}
		return df.format(dirSize/1024f/1024f) + "M";
	}
	
	/**
	 * 创建文件路径 <br/>
	 * @param [dir]-[路径名] <br/>
	 */
	public static String getStructureDirs(String dir) {
		String path = Environment.getExternalStorageDirectory()
				+ File.separator + ROOT_DIRECTORY + File.separator + dir;
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getPath();
	}
	
	/**
	 * 判定SD卡是否挂载
	 */
	public static boolean checkSdcardMounted() {
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}
	
	
	/**
	 * 获取SD卡跟目录
	 */
	public static String getSdcardPath() {
		if(checkSdcardMounted()){
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}
	
	/**
	 * 判断SD卡上的文件夹是否存在
	 */
	public static boolean isFileExist(String path, String fileName) {
		File file = new File(path + File.separator + fileName);
		return file.exists();
	}
	/**
	 * 将一个InputStream里面的数据写入到SD卡中
	 * @param path
	 * @param fileName
	 * @param input
	 * @return
	 */
	public static File write2SDFromInput(String path, String fileName, InputStream input) {
		if (input == null) {
			return null;
		}
		File file = null;
		OutputStream output = null;
		try {
			file = new File(path, fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			
			int lenght = 0;
			int total = 0;
			if (output != null && input != null) {
				while ((lenght = input.read(buffer)) > 0) {
					output.write(buffer, 0, lenght);
					total = total + lenght;
				}
				output.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return file;
	}
	
	/**
	 * 计算sdcard上的剩余空间
	 * @return 单位MB
	 */
	public static int freeSpaceOnSd() {

		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());

		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
				.getBlockSize()) / MB;

		return (int) sdFreeMB;

	}
	/**
	 * 删除文件根据url
	 * @param filePath
	 * @return
	 */
	public static boolean delete(String filePath) {
		boolean flag = false;
		if (TextUtils.isEmpty(filePath)) {
			return flag;
		}
		File file = new File(filePath);
		if (file.exists()) {
			flag = file.delete();
		}
		return flag;
	}
	/**
	 * 删除文件
	 * @param file
	 * @return
	 */
	public static boolean delete(File file) {
		if (file == null) {
			return false;
		}
		return delete(file.getAbsoluteFile());
	}
	
	public static String getDirPath() {
		return FileUtil.getDirectoryFilePath(FileUtil.IMAGE_PATH, "webViewUploadImage.jpg");
	}

	/**
	 * 保存图片
	 * @param bitmap
	 * @return
	 */
	public static String saveBitmap(Bitmap bitmap) {
		File f = new File(getDirPath());
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bitmap != null) {
				bitmap.recycle();
			}
		}
		return f.getPath();
	}
}
